import React, {Component} from 'react';
import NavigationBar from '../../Common/NavigationBar/NavigationBar.jsx'
import DialogNative from '../../Common/Dialog/Dialog.jsx';
import DialogHeader from '../../Common/Dialog/DialogHeader.jsx';
import DialogBody from '../../Common/Dialog/DialogBody.jsx';
import DialogFooter from '../../Common/Dialog/DialogFooter.jsx';
//import Using ES6 syntax
import WeUI from 'react-weui';
//import styles
import 'weui';
import 'react-weui/build/dist/react-weui.css';
import {CSS} from '../styles/meetingRoom.css';
import $ from 'jquery';
const {
    Cells,
    Cell,
    CellHeader,
    CellBody,
    CellFooter,
    Toptips,
    Input,
    TextArea,
    Picker,
    CellsTitle,
    Dialog,
    Toast
} = WeUI;
let screenWidth = $(window).width();
let screenHeight = $(window).innerHeight();
let baseFontSize = 10 * screenWidth / 375;
export default class MeetingRoomBuyTime  extends Component {
    constructor(props) {
        super(props);
        this.LeftClick = this.LeftClick.bind(this);
        this.state = {
            showConfirmBuyTime:false,
            showProtocol:false,
            showToptips: false,
            showLoading: true,
            showToast: false,
            loadingTimer: null,
            toastTimer:null,
            topTipsMsg: "服务器错误！",
            warnTimer:null,
            style: {
                title: '购买协议',
                buttons: [
                    {
                        type: 'primary',
                        label: '确认',
                        onClick: this.hideDialog.bind(this)
                    }
                ]
            },
            data:[],
            residueTime:this.props.location.query.residueTime,
            teamName:this.props.location.query.teamName,
            confirmBuyInfo:{},
            confirmBuyId:null,
        };
    }


    showToast() {
        this.setState({showToast: true,showConfirmBuyTime:false});
        this.state.toastTimer = setTimeout(()=> {
            this.setState({showToast: false});
            location.hash = "/MeetingRoomBuyTimeHistory";
        }, 2000);
    }

    showWarn(error) {
        this.setState({showToptips: true,topTipsMsg:error, showLoading: false});
        this.state.warnTimer = setTimeout(() => {
            this.setState({showToptips: false});
        }, 2000);
    }

    hideDialog(){
        this.setState({showProtocol:false});
    }


    componentWillMount() { //组件即将被插入
        this.getRechargePackageList();
    }

    LeftClick() {

    }


    closeDialog(){
        this.setState({
            showConfirmBuyTime:false
        })
    }

    payHistory(){
        location.hash = "/MeetingRoomBuyTimeHistory";
    }

    //获取可充值的时长
    getRechargePackageList(){
        let self = this;
        fetch(getHost() + "/MeetingRoom/booking/rechargePackage",{
            method: 'GET',
            credentials: 'include'
        }).then(response => response.json())
            .then(data => {
                if(data.success){
                    self.setState({
                        data:data.data,
                        showLoading:false
                    })
                }else{
                    self.showWarn(data.error.message);
                }
            }).catch(e => {
            self.showWarn(e.error.message);
        });
    }


    //购买加油包支付信息弹框
    confirmBuyTime(id){
        for(let i = 0; i < this.state.data.length; i++){
            let temp = this.state.data[i];
            if(temp.id === id){
                this.setState({
                    confirmBuyInfo:temp,
                    showConfirmBuyTime:true,
                    confirmBuyId:id})
            }
        }
    }


    //支付
    callOrderPay(id){
        let self = this;
        fetch(getHost() + "/wxpay/createOrder/TeamMeetingRoomRecharge?teamMeetingRoomRechargeHistoryId="+id+"",{
            method: 'GET',
            credentials: 'include'
        }).then(response => response.json())
            .then(data => {
                if(data.success && data.data){
                    WeixinJSBridge.invoke(
                        'getBrandWCPayRequest',
                        data.data,
                        function (res) {
                            if (res.err_msg == "get_brand_wcpay_request:ok"){// 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。
                                markDataRequestFlag();
                                window.location.hash = '/MeetingRoomBuyTimeHistory';
                            } else {  //支付失败或者取消，直接跳转到历史账单总去。
                                window.location.hash = '/MeetingRoomBuyTimeHistory';
                            }
                        }
                    );
                }else{
                    self.showWarn(data.error.message);
                }
            }).catch(e => {
            self.showWarn(e.error.message);
        });
    }

    //确认购买加油包按钮
    confirmBuyBtn(){
        let self = this;
        let formData = new FormData();
        formData.append("id",this.state.confirmBuyId);
        fetch(getHost() + "/MeetingRoom/booking/rechargePackage/order",{
            method: 'POST',
            credentials: 'include',
            body:formData,
        }).then(response => response.json())
            .then(data => {
                if(data.success){
                    //支付
                    if(data.data.price === 0){
                        self.showToast();
                    }else{
                        this.callOrderPay(data.data.id);
                    }
                }else{
                    self.showWarn(data.error.message);
                }
            }).catch(e => {
            self.showWarn(e.error.message);
        });
    }


    render() {
        let remainHeight = screenHeight - (6.4 + 1) * baseFontSize  + "px";
        let tempArea = [];
        if(this.state.data.length > 0){
            this.state.data.map((info,index)=>{
                let item = <div className="time_box" key={index}>
                    <div className="item_time_content" onClick={this.confirmBuyTime.bind(this,info.id)}>
                    <div className="pay_time_title" style={{marginTop:info.promotionPrice >= 0 ? "0" : "1.1rem"}}>{info.timeLength}小时</div>
                    <div className="pay_time_price">原价:¥{info.price}</div>
                    {info.promotionPrice >= 0 ? <div className="pay_time_promotion">促销:¥{info.promotionPrice}</div> : ""}
                </div>
                </div>;
                tempArea.push(item);
            })
        }

        let price = null;
        if(this.state.confirmBuyInfo.promotionPrice >= 0){
            price = this.state.confirmBuyInfo.promotionPrice;
        }else{
            price = this.state.confirmBuyInfo.price;
        }
        return (
            <div>
                <NavigationBar Title="购买加油包" LeftBar="true" LeftTitle="返回"
                               LeftIconSrc="/iot-meeting/assets/images/common/nav_back_icon.png" LeftClick={this.LeftClick}/>
                <div className="buy_header_box">
                    <div className="headerLeft_box" onClick={this.payHistory.bind(this)}>
                        <div className="headerLeft_title">加油包充值记录</div>
                        <img src="/iot-meeting/assets/images/meetingRoom/buy_record.png" className="headerLeft_img"/>
                    </div>
                    <div className="line_div_box"><div className="line_div"/></div>
                    <div className="headerRight_box">
                        <img src="/iot-meeting/assets/images/meetingRoom/buy_residue.png" className="headerRight_img"/>
                        <div className="headerRight_title">剩余{this.state.residueTime}%</div>
                    </div>
                </div>
                <div className="buy_content_box" style={{height:remainHeight}}>
                    <div className="companyName_box">
                        <div className="blue_div"/>
                        <div className="companyName_title">充值企业:</div>
                        <div className="companyName_value">{this.state.teamName}</div>
                    </div>
                    <div style={{clear:"both"}}/>
                    <div className="blue_div"/>
                    <div className="companyName_title">选择充值时长:</div>
                    <div style={{clear:"both"}}/>
                    <div className="time_item_box">
                        {tempArea}
                    </div>
                    <div style={{clear:"both"}}/>
                    <div className="protocol_title" onClick={e=>{this.setState({showProtocol:true})}}>购买即为同意加油包购买协议>></div>
                    <DialogNative show={this.state.showConfirmBuyTime} close={this.closeDialog.bind(this)}>
                        <DialogHeader>购买信息</DialogHeader>
                        <DialogBody>
                            <div className="DialogBody_time_box">
                                <div className="DialogBody_title">时长:</div>
                                <div className="DialogBody_value">{this.state.confirmBuyInfo.timeLength}小时</div>
                            </div>
                            <div className="DialogBody_price_box">
                                <div className="DialogBody_title">价格:</div>
                                <div className="DialogBody_value">{this.state.confirmBuyInfo.price}元</div>
                            </div>
                            <div style={{clear:"both"}}/>
                            <div className="DialogBody_price_box" style={{marginBottom:"0"}}>
                                <div className="DialogBody_title">支付费用:</div>
                            </div>
                            <div className="price_value_content">¥{price}</div>
                            <div className="confirmBuy_btn" onClick={this.confirmBuyBtn.bind(this)}>确认购买加油包</div>
                        </DialogBody>
                        <DialogFooter>
                            <div>1.企业购买加油包后，预定会议室可使用加油包抵扣;</div>
                            <div>2.加油包仅限公司当前所在园区可用;</div>
                        </DialogFooter>
                    </DialogNative>
                </div>
                <Dialog type="ios" title={this.state.style.title} buttons={this.state.style.buttons} show={this.state.showProtocol}>
                    协议内容.....
                </Dialog>
                <Toast icon="success-no-circle" show={this.state.showToast}>充值成功</Toast>
                <Toast icon="loading" show={this.state.showLoading}>加载中...</Toast>
                <Toptips type="warn" show={this.state.showToptips}>
                    {this.state.topTipsMsg}
                </Toptips>
            </div>

        )
    }
}